package com.nextbusmn.server;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nextbusmn.server.services.AndroidService;
import com.nextbusmn.server.services.ErrorService;
import com.nextbusmn.server.services.MapService;
import com.nextbusmn.server.services.RouteService;
import com.nextbusmn.server.services.StopInfoService;
import com.nextbusmn.server.services.StopService;
import com.nextbusmn.server.services.UpdateService;

/**
 * 	Main controller class that receives requests from the phone and hands them off 
 * 	to the appropriate service.
 * 
 * 	@author Trent Olson
 */
public class AndroidServicesController extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	/**
	 * Receive and handle GET requests.
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws IOException, ServletException {
		
		// split up parameters from request
		String[] pairs = request.getQueryString().split("&");
		// split each parameter into key/value pair
		String[][] params = new String[pairs.length][2];
		for (int i = 0; i < pairs.length; ++i) {
			params[i] = pairs[i].split("=");
		}
		
		AndroidService service;
		
		// create appropriate service, depending on first parameter name
		if (params[0][0].equals(ServiceType.STOP_SERVICE.getFlag())) {
			service = new StopService(params, response);
		} else if (params[0][0].equals(ServiceType.ROUTE_SERVICE.getFlag())) {
			service = new RouteService(params[0][1], response);
		} else if (params[0][0].equals(ServiceType.MAP_SERVICE.getFlag())) {
			service = new MapService(params[0][1], response);
		} else if (params[0][0].equals(ServiceType.UPDATE_SERVICE.getFlag())) {
			service = new UpdateService(response);
		} else if (params[0][0].equals(ServiceType.STOP_INFO_SERVICE.getFlag())) {
			service = new StopInfoService(params[0][1], response);
		} else {
			service = 
				new ErrorService("invalid request parameters: " + request.getQueryString(), response);
		}
		
		// process the request using the service
		service.processRequest();
	}

	/**
	 * Receive and handle POST requests.
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws IOException, ServletException {
		// No post requests handled
	}
}
